package com.itcode.interceptors;

import com.itcode.exception.LoginAllowedException;
import com.itcode.pojo.Result;
import com.itcode.utils.JwtUtil;
import com.itcode.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 创建一个拦截器
     *
     * @param request  请求体
     * @param response 响应数据
     * @param handler
     * @return 是否通行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // i令牌验证
        final String token = request.getHeader("Authorization"); //请求头获取令牌
        try {

            //从Redis中获取相同的toen
            final ValueOperations operations = redisTemplate.opsForValue();
            final String redisToken = (String) operations.get(token);

            if (redisToken == null) {
                log.info("token错误，无法登录");
                throw new LoginAllowedException("token错误，无法登录");
            }

            final Map<String, Object> claims = JwtUtil.parseToken(token);

            //将业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);

            return true; //放行
        } catch (Exception e) {
            //http响应状态为401
            response.setStatus(401);
            return false; //不放行
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据，防止内存泄露
        ThreadLocalUtil.remove();
    }
}
